package com.ys.service.sys.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.bo.dto.NameValueDto;
import com.bo.util.DateUtil;
import com.ys.config.MyConfig;
import com.ys.constant.AppConstant;
import com.ys.entity.sys.YsDict;
import com.ys.entity.sys.YsSynLog;
import com.ys.enume.sys.YsSynLogEnum;
import com.ys.mapper.sys.SysMapper;
import com.ys.mapper.sys.YsSynLogMapper;
import com.ys.service.sys.YsSynLogService;
import com.ys.util.HttpUtilYs;
import com.ys.util.TxtUtil;
import com.ys.vo.R;

@Service("ysSynLogService")
public class YsSynLogServiceImpl implements YsSynLogService {

	@Autowired
	private SysMapper sysMapper;
	@Autowired
	private YsSynLogMapper ysSynLogMapper;
	
	@Override
	@Transactional
	public R syn(Integer type) {
		
		// 查找上一个同步记录
		String updateTimeMin = "2023-01-01 00:00:00";
		YsSynLog latest = new YsSynLog().setType(type).setOrderby("A.Id DESC").queryFirst();
		if (latest != null) {
			updateTimeMin = DateUtil.getYYYY_MM_DD_HH_mm_ss(latest.getCreateTime());
		}
		String tableName = YsSynLogEnum.Type.getTableName(type);
		
		// 找出需要同步的所有菜单数据
		List<Map<String, Object>> listData = sysMapper.listData(tableName, updateTimeMin);
		if (listData == null || listData.size() == 0) {
			return R.error("没有需要同步的数据");
		}
		
		// 添加同步记录
		YsSynLog entity = null;
		{
			String detail = JSON.toJSONString(listData);
			String ip = null;
			entity = YsSynLog.ysSynLog(type, detail, ip, 1);
			ysSynLogMapper.insert(entity);
		}
		
		// 发送请求到正式服务器
		Thread t = new Thread(() -> {
			
			String body = JSON.toJSONString(listData);
			String urlNotify = AppConstant.URL_SYN_FROM_TEST + "?type=" + type;
			HttpUtilYs.sendPostJSON(urlNotify, body);
		});
		t.start();
		
		return R.ok();
	}

	@Override
	public void synDict() {


		String filePath = MyConfig.getProfile() + "/sys/";
		String fileName = "dict.json";
		

		Map<String, List<NameValueDto>> MAP_KEY_OPTIONS = new HashMap<String, List<NameValueDto>>();
		// 加载字典
		List<YsDict> listYsDict = new YsDict().setStatus(1).setOrderby("A.DictKey asc, A.SortNo asc").queryList();
		for(YsDict ysDict : listYsDict) {
			String dictKey = ysDict.getDictKey();
			List<NameValueDto> listOption = MAP_KEY_OPTIONS.containsKey(dictKey) ? MAP_KEY_OPTIONS.get(dictKey) : new ArrayList<NameValueDto>();
			
			String name = ysDict.getDictName();
			String value = ysDict.getDictValue();
			listOption.add(new NameValueDto(name, value));
			MAP_KEY_OPTIONS.put(dictKey, listOption);
		}
		String content = "var MAP_DICT = " + JSON.toJSONString(MAP_KEY_OPTIONS);
		TxtUtil.writerTxtFile(filePath, fileName, content);
	}
}
